package com.sie.project.service.impl;

import com.sie.project.entity.*;
import com.sie.project.mapper.ProjectMapper;
import com.sie.project.service.ProjectService;

import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author linjinde
 */
@Service
public class ProjectServiceImpl implements ProjectService {

    String aLLClass = "0";
    DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final Map<String, String> projectMap = new HashMap<>();
    static {
        // 存储键值对
        projectMap.put("0", "Sale Project");
        projectMap.put("1", "Formal Project");
    }

    private static final Map<String, String> projectClassMap = new HashMap<>();
    static {
        // 存储键值对
        projectClassMap.put("1", "全新开发");
        projectClassMap.put("2", "衍生开发");
        projectClassMap.put("3", "软模试样");
        projectClassMap.put("4", "备模试样");
        projectClassMap.put("5", "储备项目");
    }
    @Resource
    ProjectMapper projectMapper;
    @Override
    public List<Project> getProjectsByType(String type) {
        String projectType =projectMap.get(type);
        return  projectMapper.getProjectsByType(projectType);
    }

    @Override
    public List<Project> getProjectLateByType(String type) {
        return getProjectsByTypeOnLate(type);
    }

    public List<Project> getProjectsByTypeOnLate(String type){
        //拉取所有的项目
        List<Project> projectsByType = getProjectsByType(type);
        List<Project> lateList = new ArrayList<>();
        //遍历项目
        for(Project p : projectsByType){
            //遍历所有项目任务
            List<ProjectTaskDTO> tasks = getTasks(p.getProject_id());
            for(ProjectTaskDTO task : tasks){
                if("late".equals(task.getProject_status())){
                    lateList.add(p);
                    break;
                }
            }
        }

        return  lateList;
    }

    @Override
    public int[] getProjectClassByYear(String type, String className) {
        System.out.println("type = "+type);
        System.out.println("classname ="+ className);
        // 获取当前年份
        int currentYear = LocalDate.now().getYear();
        ///声明一个长度为 12 的数组返回
        int[] monthlyCountsArray = new int[12];
        Arrays.fill(monthlyCountsArray, 0);
        List<MonthCountDTO> monthlyCounts;
        String projectType =projectMap.get(type);
        if(className.equals(aLLClass)){
            monthlyCounts = projectMapper.getMonthlyCountsByAll(currentYear, projectType);
        }else{
            String pClassName = projectClassMap.get(className);
            monthlyCounts = projectMapper.getMonthlyCounts(currentYear,projectType,pClassName);
        }

        // 输出每个月的计数
        for (MonthCountDTO monthlyCount : monthlyCounts) {
            String month =monthlyCount.getMonth();
            String count = monthlyCount.getCount();
            System.out.println("Month " + month + ": " + count);
            monthlyCountsArray[Integer.parseInt(month)-1] = Integer.parseInt(count);
        }
        return monthlyCountsArray;
    }

    @Override
    public List<ProjectSelectVo> getProjectSelect() {
        return projectMapper.getProjectSelectVoList();
    }

    @Override
    public List<ProjectTaskDTO> getProjectStatistics(String type) {
        return null;
    }

    @Override
    public Project getProjectDetail(String projectId) {
        List<Project> projectsById = projectMapper.getProjectDetail(projectId);
        return projectsById.get(0);
    }

    @Override
    public List<ProjectTarget> getProjectTargetList(String projectId) {
        return null;
    }

    @Override
    public List<ProjectMilestone> getProjectMilestoneList(String projectId) {
        List<ProjectTaskDTO> tasks = getTasks(projectId);
        System.out.println(tasks.size());
        List<String> allowedProjectTypes = Arrays.asList("1", "3", "4");
        //List<String> allowedProjectTypes = Arrays.asList("0", "2", "4");
        List<ProjectTaskDTO> milestoneTasks = tasks.stream()
                .filter(task -> allowedProjectTypes.contains(task.getTask_type()))
                //.sorted(Comparator.comparing(task -> LocalDateTime.parse(task.getStart_date(), dateTimeFormatter)))
                .collect(Collectors.toList());
        List<ProjectMilestone> miles = new ArrayList<>();

        for(ProjectTaskDTO task : milestoneTasks){
            ProjectMilestone milestone = new ProjectMilestone();
            BeanUtils.copyProperties(task,milestone);
            miles.add(milestone);
            System.out.println(milestone);
        }
        miles = miles.stream().sorted(Comparator.comparing(task -> LocalDateTime.parse(task.getStart_date(), dateTimeFormatter))).collect(Collectors.toList());
        return miles;
    }

    @Override
    public ProjectTaskStatistic getTaskStatistic(String projectId) {
        List<ProjectTaskDTO> tasks = getTasks(projectId);
        ProjectTaskStatistic projectTaskStatistic = new ProjectTaskStatistic();
        //in_progress  进行中
        //not_started 未开始
        //complete 完成
        //closed 关闭
        //aborted
        //late 延迟
        int sum = tasks.size();
        int noStart = (int) tasks.stream()
                .filter(task -> "not_started".equals(task.getProject_status()))
                .count();
        int inProgress = (int) tasks.stream()
                .filter(task -> "in_progress".equals(task.getProject_status()))
                .count();
        projectTaskStatistic.setSum(sum);
        projectTaskStatistic.setNostart(noStart);
        projectTaskStatistic.setInProgress(inProgress);
        projectTaskStatistic.setDone(0);
        projectTaskStatistic.setExtension(1);
        return projectTaskStatistic;
    }

    @Override
    public List<ProjectTaskDTO> getTasks(String projectId) {
        return projectMapper.getProjectTasks(projectId);
    }

    /**
     *  延期任务列表
     * @param projectId 项目id
     * @return 延期任务列表
     */
    @Override
    public List<ProjectTaskDTO> getTasksByExtension(String projectId) {
        System.out.println("获取延期任务");
        //延期状态值
        String targetStatus = "not_started";
        List<ProjectTaskDTO> tasks = new ArrayList<>();
        tasks = getTasks(projectId);
        return tasks.stream()
                .filter(task -> task != null && targetStatus.equals(task.getProject_status()))
                .collect(Collectors.toList());
    }

    @Override
    public List<ProjectIssues> getIssuesList(String projectId) {
        return projectMapper.getIssuesList(projectId);
    }

    @Override
    public List<ProjectRisk> getRiskList(String projectId) {
        return projectMapper.getRiskList(projectId);
    }
    @Override
    public List<IssuesStatistic> getIssuesStatistics(String projectId){
        List<ProjectIssues> issuesList = getIssuesList(projectId);
        List<IssuesStatistic> list = new ArrayList<>();

        int h = (int) issuesList.stream().filter(projectIssues -> "高".equals(projectIssues.getIr_level())).count();
        int m = (int) issuesList.stream().filter(projectIssues -> "中".equals(projectIssues.getIr_level())).count();
        int d = (int) issuesList.stream().filter(projectIssues -> "低".equals(projectIssues.getIr_level())).count();

        IssuesStatistic issuesStatisticH = new IssuesStatistic(h,"高");
        IssuesStatistic issuesStatisticM = new IssuesStatistic(h,"中");
        IssuesStatistic issuesStatisticD = new IssuesStatistic(h,"低");
        list.add(issuesStatisticH);
        list.add(issuesStatisticM);
        list.add(issuesStatisticD);
        return  list;
    }


    @Override
    public List<RiskStatistic> getRiskStatistic(String projectId) {
        List<ProjectRisk> riskList =  getRiskList(projectId);
        List<RiskStatistic> list = new ArrayList<>();

        int a = (int) riskList.stream().filter(projectRisk -> "高".equals(projectRisk.getRisk_level()) ).count();
        int b = (int) riskList.stream().filter(projectRisk -> "中".equals(projectRisk.getRisk_level()) ).count();
        int c = (int) riskList.stream().filter(projectRisk -> "低".equals(projectRisk.getRisk_level()) ).count();

        RiskStatistic riskStatisticA = new RiskStatistic(a,"高");
        RiskStatistic riskStatisticB = new RiskStatistic(b,"中");
        RiskStatistic riskStatisticC = new RiskStatistic(c,"低");

        list.add(riskStatisticA);
        list.add(riskStatisticB);
        list.add(riskStatisticC);

        return list;
    }

    @Override
    public List<ProjectMemberRes> getProjectMemberRes(String projectId) {
        return projectMapper.getMembersList(projectId);
    }
}
